package com.walixiwa.m3udownloader.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.walixiwa.m3udownloader.model.DownloadTaskModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class TaskManager {
    private static SQLiteDatabase database;
    private static TaskManager manager;
    private static final String dbName = "task.db";
    private static final String CREATE_TABLE =
            "CREATE TABLE IF NOT EXISTS task ( id integer PRIMARY KEY,name text,url text,json text)";

    public static TaskManager getInstance() {
        if (manager == null) {
            manager = new TaskManager();
        }
        return manager;
    }

    public static void init(Context context) {
        if (database != null) {
            return;
        }
        File file = context.getDatabasePath(dbName);
        database = context.openOrCreateDatabase(file.getAbsolutePath(), Context.MODE_PRIVATE, null);
        database.execSQL(CREATE_TABLE);
    }

    public void setTask(DownloadTaskModel taskModel){
        if (database != null) {
            if (!isExists(taskModel.getUrl())) {
                database.execSQL("insert into task values (null,'" + taskModel.getName() + "','" + taskModel.getUrl() + "','" + taskModel.toJson() + "')");
            } else {
                database.execSQL("update task set json = '" + taskModel.toJson() + "' where url = '" + taskModel.getUrl() + "'");
            }
        }
    }

    public boolean isExists(String url) {
        int count = 0;
        try {
            if (database != null) {
                Cursor cursor = database.rawQuery("SELECT count(*) FROM task WHERE url = '" + url + "'", null);
                if (cursor.moveToNext()) {
                    count = cursor.getInt(0);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count != 0;
    }

    /**
     * 清空
     */
    public void clear() {
        if (database != null) {
            database.execSQL("delete from task");
        }
    }

    public void delete(String url) {
        if (database != null) {
            database.execSQL("delete from task where url = '" + url + "'");
        }
    }

    public List<DownloadTaskModel> getTaskList() {
        String sql = "SELECT * FROM task";
        List<DownloadTaskModel> taskModels = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = database.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    DownloadTaskModel model = new DownloadTaskModel();
                    String json = cursor.getString(3);
                    try {
                        JSONObject object = new JSONObject(json);
                        model.setName(object.getString("name"));
                        model.setUrl(object.getString("url"));
                        model.setSpeed(object.getString("speed"));
                        model.setInfo(object.getString("info"));
                        model.setProgress(object.getInt("progress"));
                        taskModels.add(model);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ((null != cursor) && (!cursor.isClosed())) {
                cursor.close();
            }
        }
        return taskModels;
    }
}
